﻿using System;
using System.Collections.Generic;
using System.Linq;
using ScheduleParserWorkerRole;

namespace RecorderWorkerRole
{
    public class DownloadDetails
    {
        public String HumanReadableName;
        public int Length;
        public String StreamUri;
        public long ShowId { get; private set; }
    
        public byte[] DownloadedBytes = null;


        public DownloadDetails(schedule iCurrentShow)
        {
            StartTime = iCurrentShow.StartTime;
            StopTime = iCurrentShow.StopTime;
            ShowId = iCurrentShow.Id;
            Title = iCurrentShow.Title;
            ShortName = iCurrentShow.station.ShortName;
            Streams = iCurrentShow.station.AudioStreams.
                Where(stream => stream.Container == "mp3").
                OrderByDescending(stream => stream.Container).
                //wma, mp3, aac - wma is banned, mp3 is preferred, aac is fallback (oggvorbis changes the picture for some stations :) )
                ThenByDescending(stream => stream.Bitrate).
                Take(3).ToList();
        }

        public DateTime StartTime { get; private set; }
        public List<AudioStream> Streams { get; private set; }
        public DateTime StopTime { get; private set; }

        public override string ToString()
        {
            return String.Format("DownloadDetails: {0:N0} {1}", Length, HumanReadableName);
        }

        public void SetStreamForDownload(AudioStream iCurrentStream)
        {
            var aShowStopTime = StopTime;//GetShowStopTime(iCurrentShow);
            var aNow = DateTime.UtcNow;
            var aDuration = (aShowStopTime.AddSeconds(15) - aNow);
            HumanReadableName = String.Format("{0} - {2}, {4} - {1} ({5}).{3}", ShowId,
                Title,
                ShortName, iCurrentStream.Container,
                CustomDatesFormatter.GetPrintable(StartTime),
                CustomDatesFormatter.GetPrintable(StopTime - StartTime));
            Length = (int) (aDuration.TotalSeconds*iCurrentStream.Bitrate*1000)/8;
            StreamUri = iCurrentStream.Uri;
        }

        public String ShortName { get; private set; }

        public String Title { get; private set; }
    }
}